import React from 'react'
import { Badge, TabBar, Toast } from 'antd-mobile'
import {
  SmileOutline,
  UserAddOutline,
  UserOutline,
} from 'antd-mobile-icons'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'
import '@/assets/icon-font/iconfont.css'

export default function MyTabbar(props,ref) {
  const { location } = props
  const { pathname } = location
  const tabs = [
    {
      key: '/home',
      title: '首页',
      icon: <SmileOutline />,
      badge: Badge.dot,
    },
    {
      key: '/cart',
      title: '购物车',
      icon: <span className='iconfont icon-gouwuche'/>,
      badge: '5',
    },
    {
      key: localStorage.getItem('token') ? '/mine' : '/login',
      title: localStorage.getItem('token') ?'我的':'登录',
      icon:localStorage.getItem('token') ? <UserOutline /> :<UserAddOutline />,
    },
  ]
  const [activeKey, setActiveKey] = useState(pathname)
  // 点击切换路由页面
  const his = useHistory() //相当于类组件中的this.props.history
  const changePageFn = (key)=>{
    // console.log(key); //path路径
    setActiveKey(key)  //修改选中的key

    // 当跳转页面为购物车页面 需要判断用户是否登录, 登录则正常访问购物车页面,当未登录则提示请先登录并跳转到登录页
    // 要先判断访问的什么页面
    if(key=='/car'){
      if(localStorage.getItem('token')){
        // 说明已经登录
        his.push(key)
      }else{
        Toast.show({
          content:'请先登录',
          afterClose(){
            his.push('/login')
          }
        })
      }
      return
    }
    his.push(key)
   
  }
  return (
    <div style={{
      position:'fixed',
      bottom:0,
      left:0,
      width:'100%',
      backgroundColor:'white'
    }}>
      <TabBar activeKey={activeKey} onChange={changePageFn} safeArea>
          {tabs.map(item => (
            <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
          ))}
        </TabBar>
    </div>
  )
}
